<template>
  <div id="materPurchaseDia">
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="采购单详情"
      :visible.sync="inComData.materPurchaseDiaStatus"
      :fullscreen="true"
      :modal="false"
      @closed="closededitDialogStatus"
      @open="openeditDialogStatus"
    >
      <div
        style="width: 70%"
        class="dialogItem"
      >
        <el-form
          :model="editForm.biDto"
          :rules="rules"
          ref="editForm"
          label-width="150px"
          style="width: 100%; margin: 0 auto"
        >
          <el-row class="titleInfo mb-10">基础信息</el-row>
          <el-row
            type="flex"
            justify="start"
            align="middle"
            class="itemDiv mb-10"
          >
            <el-col :span="7"
              ><el-form-item
                label="关联计划"
                prop="planId"
              >
                <el-select
                  v-model="editForm.biDto.planName"
                  placeholder="请选择"
                  style="width: 100%"
                  disabled
                >
                  <el-option
                    v-for="(item, index) in planOptions"
                    :key="index + 'p'"
                    :label="item.planName"
                    :value="item.id"
                  >
                  </el-option> </el-select></el-form-item
            ></el-col>
            <el-col :span="7"
              ><el-form-item
                label="采购名称"
                prop="purchaseName"
              >
                <el-input
                  disabled
                  v-model="editForm.biDto.purchaseName"
                  placeholder="请输入采购名称，长度2-50个文字"
                ></el-input></el-form-item
            ></el-col>
          </el-row>
          <el-row
            class="titleInfo mb-10"
            type="flex"
            justify="space-between"
            align="middle"
          >
            <el-col>采购信息</el-col>
          </el-row>
          <el-row
            v-for="(item, index) in editForm.biDto.purchaseItemInfos"
            :key="index + 'sg'"
            class="itemDiv mb-20"
          >
            <el-row style="color: #409eff"> {{ index + 1 }}、 </el-row>
            <hr
              style="
                background-color: #40a0ff94;
                height: 1px;
                border: none;
                margin-bottom: 10px;
              "
            />

            <el-form-item
              label-width="0"
              prop="purchaseItemInfos"
            >
              <el-row
                type="flex"
                justify="space-between"
                align="middle"
              >
                <el-col
                  :span="7"
                  class="flexCenter"
                >
                  <el-form-item
                    label-width="150px"
                    label="供应商："
                    :prop="'purchaseItemInfos.' + index + '.supplierId'"
                    :rules="supplierIdRules"
                  >
                    <el-select
                      disabled
                      style="min-width: 280px"
                      v-model="item.supplierName"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="(item, index) in supplierInfoOptions"
                        :key="index + 's'"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option> </el-select
                  ></el-form-item>
                </el-col>
                <el-col
                  :span="7"
                  class="flexCenter"
                >
                  <el-form-item
                    label-width="150px"
                    label="物料名称："
                    :prop="'purchaseItemInfos.' + index + '.materialId'"
                    :rules="materialIdRules"
                  >
                    <el-select
                      disabled
                      style="min-width: 280px"
                      v-model="item.materialName"
                      placeholder="请选择"
                      value-key="id"
                    >
                      <el-option
                        v-for="(el, index) in item.typeOptions"
                        :key="index + 'd'"
                        :label="el.model"
                        :value="el.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col
                  :span="7"
                  class="flexCenter"
                  ><el-form-item
                    label-width="150px"
                    label="规格型号："
                    :prop="'purchaseItemInfos.' + index + '.modelId'"
                    :rules="modelIdRules"
                  >
                    <el-select
                      disabled
                      style="min-width: 280px"
                      v-model="item.modelName"
                      placeholder="请选择"
                      value-key="id"
                      @change="changeModel($event, item)"
                    >
                      <el-option
                        v-for="(el, index) in item.typeOptions"
                        :key="index + 'd'"
                        :label="el.model"
                        :value="el.id"
                      >
                      </el-option> </el-select
                  ></el-form-item>
                </el-col>
              </el-row>
            </el-form-item>

            <el-row
              type="flex"
              justify="space-between"
              align="middle"
            >
              <el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="计量单位："
                  :prop="'purchaseItemInfos.' + index + '.unit'"
                  :rules="unitRules"
                  ><el-input
                    disabled
                    style="min-width: 280px"
                    v-model="item.unit"
                    placeholder="请选择"
                  >
                  </el-input
                ></el-form-item>
              </el-col>
              <el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="质量技术要求："
                  :prop="
                    'purchaseItemInfos.' + index + '.technicalRequirements'
                  "
                  :rules="technicalRequirementsRules"
                  ><el-input
                    disabled
                    style="min-width: 280px"
                    v-model="item.technicalRequirements"
                    placeholder="请选择"
                  >
                  </el-input
                ></el-form-item>
              </el-col>
              <el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="计划单价："
                  :prop="'purchaseItemInfos.' + index + '.planPrice'"
                  :rules="planPriceRules"
                >
                  <el-input
                    disabled
                    style="min-width: 280px"
                    v-model="item.planPrice"
                    type="number"
                    placeholder="请选择"
                  >
                  </el-input
                ></el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
            >
              <el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="需用数量："
                  :prop="'purchaseItemInfos.' + index + '.quantityRequired'"
                  :rules="quantityRequiredRules"
                >
                  <el-input
                    disabled
                    style="min-width: 280px"
                    v-model="item.quantityRequired"
                    type="number"
                    placeholder="请选择"
                  >
                  </el-input
                ></el-form-item>
                <div class="w-100"></div>
              </el-col>
              <el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="库存数量："
                  :prop="'purchaseItemInfos.' + index + '.quantityStock'"
                  :rules="quantityStockRules"
                >
                  <el-input
                    disabled
                    style="min-width: 280px"
                    v-model="item.quantityStock"
                    type="number"
                    placeholder="请选择"
                  >
                  </el-input>
                </el-form-item> </el-col
              ><el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="储备数量："
                  :prop="'purchaseItemInfos.' + index + '.quantityReserve'"
                  :rules="quantityReserveRules"
                >
                  <el-input
                    disabled
                    style="min-width: 280px"
                    v-model="item.quantityReserve"
                    type="number"
                    placeholder="请选择"
                  >
                  </el-input
                ></el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
            >
              <el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="采购数量："
                  :prop="'purchaseItemInfos.' + index + '.quantityPurchase'"
                  :rules="quantityPurchaseRules"
                  ><el-input
                    disabled
                    style="min-width: 280px"
                    v-model="item.quantityPurchase"
                    type="number"
                    placeholder="请选择"
                  >
                  </el-input
                ></el-form-item>
              </el-col>
              <el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="计划金额："
                  :prop="'purchaseItemInfos.' + index + '.planTotalPrice'"
                  :rules="planTotalPriceRules"
                >
                  <el-input
                    disabled
                    style="min-width: 280px"
                    v-model="item.planTotalPrice"
                    type="number"
                    placeholder="请选择"
                  >
                  </el-input
                ></el-form-item> </el-col
              ><el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="计划进场时间："
                  :prop="'purchaseItemInfos.' + index + '.planDate'"
                  :rules="planDateRules"
                  ><el-date-picker
                    disabled
                    style="min-width: 280px"
                    v-model="item.planDate"
                    type="date"
                    placeholder="选择日期"
                  >
                  </el-date-picker
                ></el-form-item>
              </el-col>
            </el-row>
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
            >
              <el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="备注："
                >
                  <el-input
                    disabled
                    style="min-width: 280px"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请输入内容"
                    v-model="item.remark"
                  >
                  </el-input
                ></el-form-item>
              </el-col>
              <el-col
                :span="7"
                class="flexCenter"
              >
                <el-form-item
                  label-width="150px"
                  label="相关文件："
                  ><div>
                    <p
                      class="fileInfos"
                      v-for="(f, index) in item.fileInfos"
                      :key="index + 'fi'"
                      @click="fileDetailHandler(f)"
                    >
                      <i
                        :class="
                          /\.(jpeg|jpg|gif|png|bmp)$/i.test(f.name)
                            ? 'el-icon-picture-outline'
                            : 'el-icon-document'
                        "
                      ></i>
                      {{ f.name }}
                    </p>
                  </div>
                </el-form-item>
              </el-col>
              <el-col
                :span="7"
                class="text-r"
              >
              </el-col>
            </el-row>
          </el-row>
        </el-form>
        <el-row
          type="flex"
          justify="center"
          slot="footer"
        >
          <div>
            <el-button
              v-if="editForm.biDto.purchaseItemInfos[0].permission"
              type="warning"
              @click="auditHandler('detail', editForm.biDto)"
              >审核</el-button
            >
            <el-button @click="inComData.materPurchaseDiaStatus = false"
              >返回</el-button
            >
          </div>
        </el-row>
      </div>

      <div
        style="width: calc(30% - 20px); height: 100%; margin-left: 20px"
        class="dialogItem"
      >
        <approxFlow
          ref="approxFlow"
          :steps="steps"
        ></approxFlow>
      </div>
    </el-dialog>

    <previewImg ref="previewImg"></previewImg>

    <importData
      ref="importData"
      :approxFlowData="approxFlowData"
      :templateUrl="templateUrl"
      :importDataData="importDataData"
    ></importData>

    <toExamine
      ref="toExamine"
      :steps="steps"
      :approxForm="approxForm"
      :toExamineData="toExamineData"
    ></toExamine>
  </div>
</template>

<script>
import {
  getPurchaseInfoPage,
  addPurchaseInfo,
  deletePurchaseInfo,
  getPurchaseItemInfoDetail,
  addPurchaseInfoDraft,
  updatePurchaseInfo,
  getPlanList,
  geSupplierInfoList,
  getMaterialTree,
  getMaterialDetail,
  getMaterialTypeDetail,
  getPurchaseInfoExport,
  getInventoryData,
  uploadFile,
  terminatePlan,
  executeTaskPlan,
  getNextNodeAssignWay,
  downloadFile,
  importPurchaseInfo,
} from '/src/http/materialDispatch/materPurchase.js'
import download from '/src/utils/downLoad.js'
import {
  getProcessLog,
  getEnableUserList,
  deleteFile,
  deleteFileList,
} from '/src/http/commonApi.js'
import { throttle } from '/src/utils/index.js'
import importData from '/src/component/assembly/importData.vue'
import approxFlow from '/src/component/assembly/approxFlow.vue'
import toExamine from '/src/component/assembly/toExamine.vue'

import previewImg from '/src/component/previewImg/previewImg.vue'
export default {
  components: {
    importData,
    approxFlow,
    toExamine,
    previewImg,
  },
  data() {
    return {
      ccListStatus: false,
      manOptions: [],
      ccList: [],

      approxFlowData: {},
      templateUrl: '/excel/物资采购导入模板.xlsx',
      importDataData: {
        importDataStatus: false,
      },

      toExamineData: {
        toExamineDataStatus: false,
        isSearch: false,
      },
      approxForm: {
        approveOperation: '1',

        opinion: '发起了审批',
      },
      steps: {},
      key: '',
      planDate: [],
      materialArr: [],
      materialArrOptions: [],
      modelId: null,
      typeSearchOptions: [],
      multipleSelection: [],
      multipleSelectionIds: [],
      renderData: [],

      total: 0,
      pageSize: 10,
      pageNum: 1,
      isSearch: false,

      editDialogStatus: false,
      editTitle: '',
      isDraft: false,
      editForm: {
        assignees: [],
        opinion: '',
        ccList: [],
        biDto: {
          id: null,
          planId: null,
          purchaseName: '',
          purchaseItemInfos: [
            {
              id: null,
              supplierId: null,
              typeOptions: [],
              modelId: null,
              materialId: null,
              unit: '',
              technicalRequirements: '',
              planPrice: null,
              quantityRequired: null,
              quantityStock: null,
              quantityReserve: null,
              quantityPurchase: null,
              planTotalPrice: null,
              planDate: '',
              remark: '',
              fileInfos: [],
            },
          ],
        },
      },
      rules: {
        planId: [
          { required: true, message: '请选择关联计划', trigger: 'change' },
        ],
        purchaseName: [
          { required: true, message: '请输入采购名称', trigger: 'change' },
          {
            min: 2,
            max: 50,
            message: '长度在 2 到 50 个文字',
            trigger: 'blur',
          },
        ],
      },
      supplierIdRules: [
        { required: true, message: '请选择供应商', trigger: 'change' },
      ],
      materialIdRules: [
        { required: true, message: '请选择物料名称', trigger: 'change' },
      ],
      modelIdRules: [
        { required: true, message: '请选择规格型号', trigger: 'change' },
      ],
      unitRules: [
        { required: true, message: '请选择计量单位', trigger: 'change' },
      ],
      technicalRequirementsRules: [
        { required: true, message: '请输入质量技术要求', trigger: 'change' },
      ],
      planPriceRules: [
        { required: true, message: '请输入计划单价', trigger: 'change' },
      ],
      quantityRequiredRules: [
        { required: true, message: '请输入需用数量', trigger: 'change' },
      ],
      quantityStockRules: [
        { required: true, message: '请输入库存数量', trigger: 'change' },
      ],
      quantityReserveRules: [
        { required: true, message: '请输入储备数量', trigger: 'change' },
      ],
      quantityPurchaseRules: [
        { required: true, message: '请输入采购数量', trigger: 'change' },
      ],
      planTotalPriceRules: [
        { required: true, message: '请输入计划金额', trigger: 'change' },
      ],
      planDateRules: [
        { required: true, message: '请选择计划进场时间', trigger: 'change' },
      ],

      planOptions: [],
      supplierInfoOptions: [],
      materialOptions: [],
      typeOptions: [],
      uploadUrl: '',
      fileList: [],
      deleteArrIds: [],

      spanArr: [],

      messageShown: false,
      detailName: '',

      detailData: {},
    }
  },
  props: {
    inComData: Object,
  },
  mounted() {
    getMaterialTree().then((res) => {
      if (res.code == 200) {
        this.materialArrOptions = res.data
      }
    })
    this.getPurchaseInfoPageApi()
    this.getPlanListApi()
    this.geSupplierInfoListApi()
    this.getMaterialTreeApi()
  },

  methods: {
    getPurchaseInfoPageApi() {},

    fileDetailHandler(item) {
      if (/\.(jpeg|jpg|gif|png|bmp)$/i.test(item.name)) {
        downloadFile({ path: item.path }).then((res) => {
          let url = URL.createObjectURL(res)

          this.$refs['previewImg'].showImg(url, item.name)
        })
      } else {
        downloadFile({ path: item.path }).then((res) => {
          download.stream(res, item.name)
        })
      }
    },
    closededitDialogStatus() {
      this.inComData.materPurchaseDiaStatus = false
    },
    openeditDialogStatus() {
      this.seeDetail(this.inComData.data)
    },

    seeDetail(data) {
      console.log('data::: ', data)
      getPurchaseItemInfoDetail(data.id).then((res) => {
        console.log('getPurchaseInfoDetail::: ', res)
        if (res.code == 200) {
          this.editForm.biDto = res.data
        }
      })
      if (data.state !== 'draft') {
        getProcessLog({ id: data.orderId }).then((res) => {
          if (res.code == 200) {
            this.steps = res.data
            this.steps.state = this.editForm.biDto.state
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },

    toExamineStatusChange() {
      this.importDataData.importDataStatus = true
    },

    toExamineFun() {
      if (Object.keys(this.detailData).length > 0) {
        this.startProcess(this.detailData)
      } else {
        this.startProcess(this.editForm.biDto)
      }
    },
    materialChangeHand(v) {
      getMaterialDetail(v[v.length - 1]).then((res) => {
        this.typeSearchOptions = []
        if (res.code == 200) {
          this.typeSearchOptions = res.data
          this.modelId = null
        }
      })
    },
    toExamineDataClean() {
      this.toExamineData = {
        toExamineDataStatus: false,
        isSearch: false,
      }
      this.approxForm = {
        approveOperation: '1',

        opinion: '',
      }
    },

    auditHandler(name = '', data) {
      console.log('data::: ', data)
      if (name === 'detail') {
        this.detailName = 'detail'
        this.$confirm(`确认要审核【${data.purchaseName}】？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.approxForm.opinion = ''

            getProcessLog({ id: data.purchaseItemInfos[0].orderId }).then(
              (res) => {
                if (res.code == 200) {
                  this.toExamineData.toExamineDataStatus = true
                  this.steps = res.data
                } else {
                  this.$message.error(res.message)
                }
              }
            )
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消审批',
            })
          })
      } else {
        if (this.multipleSelection.length > 1) {
          this.$message({
            message: '审批不能选择多条',
            type: 'warning',
          })
        } else if (this.multipleSelection.length == 0) {
          this.$message({
            message: '未选择物资采购',
            type: 'warning',
          })
        } else if (
          this.multipleSelection[0].purchaseItemInfos[0].state === 'draft'
        ) {
          this.$message.warning('该物资采购为草稿，不能进行审批')
        } else if (!this.multipleSelection[0].purchaseItemInfos[0].permission) {
          if (this.multipleSelection[0].state === 'completed') {
            this.$message.warning('该物资采购已完成审批')
          } else if (
            this.multipleSelection[0].purchaseItemInfos[0].state ===
            'terminated'
          ) {
            this.$message.warning('该物资采购已结束审批')
          } else {
            this.$message.warning('无审批权限')
          }
        } else {
          this.$confirm(
            `确认要审核选中的【${this.multipleSelection[0].purchaseName}】？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              this.approxForm.opinion = ''

              getProcessLog({
                id: this.multipleSelection[0].purchaseItemInfos[0].orderId,
              }).then((res) => {
                if (res.code == 200) {
                  this.toExamineData.toExamineDataStatus = true
                  this.steps = res.data
                } else {
                  this.$message.error(res.message)
                }
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消审批',
              })
            })
        }
      }
    },

    downloadFileHandler(item) {
      downloadFile({ path: item.path }).then((res) => {
        download.word(res, item.name)
      })
    },

    detailHandler(data) {
      this.editTitle = '详情'
      this.editDialogStatus = true
      if (data.state === 'draft') {
        this.isDraft = true
      } else {
        this.isDraft = false
      }
      this.getPurchaseInfoDetailApi(data)
    },

    editHandler(data) {
      this.editTitle = '编辑'
      this.editDialogStatus = true
      this.getPurchaseInfoDetailApi(data)
    },

    changeMaterial(val, item) {
      item.modelId = null
      this.getMaterialDetailApi(val[val.length - 1], item)
    },

    changeModel(val, item) {
      item.typeOptions.forEach((el) => {
        if (el.id == val) {
          item.unit = el.unit
        }
      })
      this.getInventoryDataApi([item.materialId[1], val], item)
    },
    /**
     * 上传文件
     */

    handleRemove(file, fileList, item) {
      console.log('item::: ', item)
      this.$confirm(`确定移除 ${file.name}？`)
        .then(() => {
          if (item.fileIds) {
            let fileIndex
            item.fileIds.forEach((el, index) => {
              if (el == file.id) {
                if (file.path) {
                  this.deleteArrIds.push(file.id)
                }
                fileIndex = index
              }
            })
            delete item.fileIds[fileIndex]
          }
        })
        .catch(() => {
          fileList.push(file)
          this.$message.info('已取消删除')
          return false
        })
      console.log('item::: ', item)
      return fileList
    },

    uploadChange(file, fileList, item) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        fileList.splice(fileList.length - 1, 1)
        this.$message.info('上传文件大小不能超过 10MB！')
        return
      }

      let a = 0
      fileList.forEach((item, idx) => {
        if (file.name === item.name) {
          a++
          if (a === 2) {
            this.$message({
              message: `文件名[${file.name}]不能重复`,
              type: 'info',
            })
            fileList.splice(idx, 1)
          }
        }
      })
      item.fileList = JSON.parse(JSON.stringify(fileList))

      fileList = fileList.filter((a) => {
        if (a.raw) {
          return a
        }
        return a.raw
      })
      item.fileInfos = new FormData()
      fileList.forEach((el) => {
        if (el.raw) {
          item.fileInfos.append('file', el.raw)
        }
      })
      item.fileInfos.append('biId', item.id)
      item.fileInfos.append('type', '/ml/purchase/info')
    },

    submitHandler(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ccList = []
          this.getEnableUserListApi()
          this.ccListStatus = true
        } else {
          alert('请检查输入项是否填写完整')
          return false
        }
      })
    },

    saveDraftHandler(formName) {
      if (this.editTitle == '新增') {
        this.addPurchaseInfoDraftApi(this.editForm.biDto)
      } else {
        this.updatePurchaseInfoApi(this.editForm.biDto)
      }
    },

    cancelHandler(formName) {
      this.editDialogStatus = false
      let that = this
      setTimeout(() => {
        that.$refs[formName].resetFields()
      }, 300)
    },

    startProcess(biDto) {
      console.log('biDto::: ', biDto)
      let params = {
        state: biDto.purchaseItemInfos[0].state,
        type: 'mlPurchaseInfo',
      }
      if (this.approxForm.approveOperation === '0') {
        this.terminatePlanApi(biDto.purchaseItemInfos[0].id)
      } else if (this.approxForm.approveOperation === '1') {
        getNextNodeAssignWay(params).then((res) => {
          if (res.code == 200) {
            if (!res.data) {
              this.executeTaskPlanApi(0, biDto)
            } else if (res.data.assignWay === 0 || res.data.assignWay === 2) {
              if (
                biDto.purchaseItemInfos[0].state == 'draft' ||
                biDto.purchaseItemInfos[0].state == undefined
              ) {
                let params = biDto
                params.purchaseItemInfos.forEach((el) => {
                  console.log('el::: ', el)
                  el.fileIds = []
                  if (el.fileInfos.length > 0) {
                    el.fileInfos.forEach((item) => {
                      el.fileIds.push(item.id)
                    })
                  }
                })
                console.log('params::: ', params)
                this.addPurchaseInfoApi(params)
              } else {
                console.log('2::: ', 2)

                this.executeTaskPlanApi(0, biDto)
              }
            } else if (res.data.assignWay === 1) {
            }
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },

    getEnableUserListApi() {
      getEnableUserList().then((res) => {
        if (res.code == 200) {
          this.manOptions = res.data
        }
      })
    },

    getPlanListApi() {
      getPlanList().then((res) => {
        if (res.code == 200) {
          this.planOptions = res.data
        }
      })
    },

    geSupplierInfoListApi() {
      geSupplierInfoList().then((res) => {
        if (res.code == 200) {
          this.supplierInfoOptions = res.data
        }
      })
    },

    getMaterialTreeApi() {
      getMaterialTree().then((res) => {
        if (res.code == 200) {
          this.materialOptions = res.data
        }
      })
    },

    async getMaterialTypeDetailApi(item) {
      getMaterialTypeDetail(item.materialId).then((res) => {
        if (res.code == 200) {
          if (res.data.parentIds == null) {
            item.materialId = [res.data.pid, res.data.id]
          } else {
            item.materialId = res.data.parentIds.split(',').map(Number)
            item.materialId.shift()
            item.materialId.push(res.data.id)
          }
        }
      })
    },
    async a(str, id, item) {
      await this.getMaterialTreeApi()

      if (str instanceof Array) {
        item.materialId = str
      } else {
        item.materialId = str.split(',').map(Number)
        item.materialId.shift()
        item.materialId.push(id)
      }
    },

    getMaterialDetailApi(id, item) {
      getMaterialDetail(id).then((res) => {
        if (res.code == 200) {
          item.typeOptions = res.data
        }
      })
    },

    getInventoryDataApi(arr, item) {
      getInventoryData(arr).then((res) => {
        if (res.code == 200 && res.data) {
          item.quantityStock = Number(res.data.quantityStock)
        } else {
          item.quantityStock = 0
          this.$message.info('暂未查询到库存')
        }
      })
    },

    flattenTree(tree) {
      let that = this
      let result = []
      for (let item of tree) {
        let { purchaseItemInfos, ...rest } = item
        if (purchaseItemInfos) {
          purchaseItemInfos = purchaseItemInfos.map((el) => {
            let { id, ...rest } = el
            return { cid: id, purchaseItemInfos1: [el], ...rest }
          })
          result.push(
            ...that.flattenTree(purchaseItemInfos).map((subItem) => ({
              ...rest,
              ...subItem,
            }))
          )
        } else {
          result.push(rest)
        }
      }
      return result
    },

    getPurchaseInfoDetailApi(data) {
      getPurchaseInfoDetail(data.id).then((res) => {
        console.log('getPurchaseInfoDetail::: ', res)
        if (res.code == 200) {
          this.editForm.biDto = res.data
        }
      })
      if (data.state !== 'draft') {
        getProcessLog({ id: data.orderId }).then((res) => {
          if (res.code == 200) {
            this.steps = res.data
            this.steps.state = this.editForm.biDto.state
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },

    addPurchaseInfoApi(params) {
      let b = JSON.parse(JSON.stringify(params))
      if (this.deleteArrIds && this.deleteArrIds.length > 0) {
        deleteFileList(this.deleteArrIds)
          .then((res) => {
            if (res.code == 200) {
            }
          })
          .catch((err) => {})
      }

      let a = {
        assignees: [],
        opinion: this.approxForm.opinion,
        ccList: this.ccList,
        biDto: params,
      }
      a.biDto.purchaseItemInfos.forEach((item) => {
        if (item.fileIds && item.fileIds.length > 0) {
          item.fileIds = item.fileIds.filter((el) => {
            if (el) {
              return el
            }
          })
          item.fileIds = [...new Set(item.fileIds)]
        }

        if (item.fileList === undefined || item.fileList.length == 0) {
          if (item.materialId) {
            item.materialId = item.materialId[item.materialId.length - 1]
          }
          console.log('1,a::: ', 1, a)
          addPurchaseInfo(a).then((res) => {
            if (res.code == 200) {
              this.ccListStatus = false
              this.editDialogStatus = false
              this.pageNum = 1
              this.getPurchaseInfoPageApi(
                1,
                this.pageSize,
                this.key,
                this.planDate,
                this.materialArr[this.materialArr.length - 1],
                this.modelId
              )
              throttle(this.showMessage(), 2000)()
            } else {
              this.ccListStatus = true
              params.purchaseItemInfos.forEach((item) => {
                b.purchaseItemInfos.forEach((el) => {
                  if (item.id === el.id) {
                    item.materialId = el.materialId
                  }
                })
              })
            }
          })
        } else {
          if (item.fileIds === undefined) {
            item.fileIds = []
          }

          uploadFile(item.fileInfos).then((res) => {
            if (res.code == 200) {
              res.data.forEach((el) => {
                item.fileIds.push(el.id)
              })
              if (item.materialId) {
                item.materialId = item.materialId[item.materialId.length - 1]
              }
              throttle(
                addPurchaseInfo(a).then((res) => {
                  if (res.code == 200) {
                    this.ccListStatus = false
                    this.editDialogStatus = false
                    this.pageNum = 1
                    this.getPurchaseInfoPageApi(
                      1,
                      this.pageSize,
                      this.key,
                      this.planDate,
                      this.materialArr[this.materialArr.length - 1],
                      this.modelId
                    )
                    throttle(this.showMessage(), 2000)()
                  } else {
                    this.ccListStatus = true
                    this.$message.error(res.message)
                    params.purchaseItemInfos.forEach((it) => {
                      b.purchaseItemInfos.forEach((el) => {
                        if (it.id === el.id) {
                          it.materialId = el.materialId
                        }
                      })
                    })
                  }
                }),
                2000
              )
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    showMessage() {
      if (!this.messageShown) {
        this.$message.success('新增物资采购划并成功发起审批')
        this.messageShown = true

        setTimeout(() => {
          this.messageShown = false
        }, 2000)
      }
    },

    deletePurchaseInfoApi(id) {
      this.$confirm('是否删除该物资采购？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deletePurchaseInfo(id).then((res) => {
            if (res.code == 200) {
              this.$message.success('删除成功')
              this.pageNum = 1
              this.getPurchaseInfoPageApi(
                1,
                this.pageSize,
                this.key,
                this.planDate,
                this.materialArr[this.materialArr.length - 1],
                this.modelId
              )
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },

    addPurchaseInfoDraftApi(params) {
      let b = JSON.parse(JSON.stringify(params))
      const uploadPromises = params.purchaseItemInfos.map(async (el) => {
        if (el.materialId) {
          el.materialId = el.materialId[el.materialId.length - 1]
        }
        if (el.fileList) {
          return await uploadFile(el.fileInfos).then((res) => {
            if (res.code == 200) {
              el.fileIds = []
              res.data.forEach((item) => {
                el.fileIds.push(item.id)
              })
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })

      Promise.all(uploadPromises).then(() => {
        addPurchaseInfoDraft(params).then((res) => {
          if (res.code == 200) {
            this.$message.success('新增草稿成功')
            this.editDialogStatus = false
            this.pageNum = 1
            this.getPurchaseInfoPageApi(
              1,
              this.pageSize,
              this.key,
              this.planDate,
              this.materialArr[this.materialArr.length - 1],
              this.modelId
            )
          } else {
            this.$message.error(res.message)
            params.purchaseItemInfos.forEach((item) => {
              b.purchaseItemInfos.forEach((el) => {
                if (item.id === el.id && el.materialId) {
                  item.materialId = el.materialId
                }
              })
            })
          }
        })
      })
    },

    updatePurchaseInfoApi(params) {
      let b = JSON.parse(JSON.stringify(params))
      if (this.deleteArrIds && this.deleteArrIds.length > 0) {
        deleteFileList(this.deleteArrIds)
          .then((res) => {
            if (res.code == 200) {
            }
          })
          .catch((err) => {})
      }
      const uploadPromises = params.purchaseItemInfos.map((el) => {
        if (el.fileInfos) {
          return uploadFile(el.fileInfos).then((res) => {
            if (res.code == 200) {
              res.data.forEach((item) => {
                el.fileIds.push(item.id)
              })
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })

      Promise.all(uploadPromises).then(() => {
        params.purchaseItemInfos.forEach((item) => {
          if (item.materialId) {
            item.materialId = item.materialId[item.materialId.length - 1]
          }
        })
        updatePurchaseInfo(params).then((res) => {
          if (res.code == 200) {
            this.$message.success('编辑成功')
            this.editDialogStatus = false
            this.getPurchaseInfoPageApi(
              this.pageNum,
              this.pageSize,
              this.key,
              this.planDate,
              this.materialArr[this.materialArr.length - 1],
              this.modelId
            )
          } else {
            this.$message.error(res.message)
            params.purchaseItemInfos.forEach((item) => {
              b.purchaseItemInfos.forEach((el) => {
                if (item.id === el.id && el.materialId) {
                  item.materialId = el.materialId
                }
              })
            })
          }
        })
      })
    },

    getNextNodeAssignWayApi(state = '', type = 'mlPurchaseInfo') {
      let params = {
        state,
        type,
      }
      getNextNodeAssignWay(params).then((res) => {
        if (res.code == 200) {
          this.editForm.assignees = res.data.assignees
          this.editForm.ccList = res.data.ccList
        } else {
          this.$message.error(res.message)
        }
      })
    },

    terminatePlanApi(id) {
      terminatePlan(id).then((res) => {
        if (res.code == 200) {
          this.$message.success('终止成功')
          this.toExamineData.toExamineDataStatus = false
          this.inComData.materPurchaseDiaStatus = false
          this.detailData = {}
          this.$parent.workbenchTaskCountyApi()
          this.$parent.shuaxin()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    executeTaskPlanApi(type, biDto) {
      console.log('biDto::: ', biDto)
      if (type == 0) {
        let params = {
          assignees: [],
          opinion: this.approxForm.opinion,
          ccList: this.ccList,
          biDto: biDto.purchaseItemInfos[0],
        }
        if (params.biDto.fileInfos && params.biDto.fileInfos.length > 0) {
          params.biDto.fileIds = []
          params.biDto.fileInfos.forEach((el) => {
            params.biDto.fileIds.push(el.id)
          })
        }
        console.log('params::: ', params)

        executeTaskPlan(params).then((res) => {
          if (res.code == 200) {
            this.$message.success('审核成功')

            this.toExamineData.toExamineDataStatus = false
            this.inComData.materPurchaseDiaStatus = false
            this.detailData = {}
            this.$parent.workbenchTaskCountyApi()
            this.$parent.shuaxin()
          } else {
            this.$message.error(res.message)
            this.detailData = {}
          }
        })
      } else {
        this.toExamineData.toExamineDataStatus = false
        this.inComData.materPurchaseDiaStatus = false
        this.terminatePlanApi(biDto.purchaseItemInfos[0].id)
      }
    },

    getPurchaseInfoExportApi(params) {
      getPurchaseInfoExport(params).then((res) => {
        download.excel(res, `物资采购${Date.now()}.xlsx`)
      })
    },
    toExamineDataClean() {
      this.toExamineData = {
        toExamineDataStatus: false,
        isSearch: false,
      }
      this.approxForm = {
        approveOperation: '1',

        opinion: '',
      }
    },
  },
}
</script>

<style lang="less" scoped>
#warehouseReceipt {
  width: 100%;
  margin: 0 auto;
}
:deep(.el-dialog__header) {
  background-color: rgb(43, 43, 53);
}
:deep(.el-dialog__title) {
  color: #fff;
}
.topDiv {
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 1px 1px 10px 1px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}
.footerDiv {
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 1px 1px 10px 1px rgba(0, 0, 0, 0.1);
}
.flexCenter {
  display: flex;
  align-items: center;
}
.mb-10 {
  margin-bottom: 10px;
}
.mb-20 {
  margin-bottom: 20px;
}
.w-100 {
  width: 100px;
}
.text-r {
  text-align: right;
}
.titleInfo {
  color: #409eff;
  margin-bottom: 10px;
}

:deep(.nostar .el-form-item__label:before) {
  display: none !important;
}
.noFile {
  color: #d6d6d6;
  font-size: 12px;
}
.haveFile {
  color: #519fec;
  cursor: pointer;
}
.haveFile:hover {
  color: #0080ff;
}
.itemDiv {
  border: 1px solid #e8e8e9;
  border-radius: 20px;
  padding: 20px;
}
.dialogItem {
  float: left;
}
:deep(.el-input.is-disabled .el-input__inner) {
  color: #606266;
  background-color: #fcfcfc;
}
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #606266;
  background-color: #fcfcfc;
}
:deep(.cellpadding0 .cell) {
  padding: 0 !important;
}
.fileInfos:hover {
  color: #409eff;
  cursor: pointer;
}
</style>
